What is generate-function?
The generate-function package is a tool for creating dynamic functions in JavaScript. It allows developers to programmatically build new functions as strings and then compile them into executable functions. This can be particularly useful for cases where you need to generate custom logic at runtime based on certain conditions, or when you want to optimize performance by compiling a function once and reusing it multiple times.
What are generate-function's main functionalities?
Creating a simple function
This feature allows you to create a simple function that returns a static value. The code sample demonstrates generating a function that returns the number 42.
var gen = require('generate-function');
var fn = gen()
.body('return 42;')
.toFunction();
console.log(fn()); // 42
Creating a function with parameters
This feature allows you to create a function with parameters. The code sample demonstrates generating a function that takes two parameters and returns their sum.
var gen = require('generate-function');
var fn = gen()
.param('a', 'b')
.body('return a + b;')
.toFunction();
console.log(fn(1, 2)); // 3
Creating a function with a complex body
This feature allows you to create a function with a more complex body, including logic and control structures. The code sample demonstrates generating a function that compares two values and returns the larger one.
var gen = require('generate-function');
var fn = gen()
.body('if (a > b) { return a; } else { return b; }')
.toFunction();
console.log(fn(5, 3)); // 5
Other packages similar to generate-function
new-function
The new-function package is similar to generate-function in that it allows you to create new functions from strings. However, it does not provide the same level of API for building the function body and parameters programmatically.
function-plot
The function-plot package is designed for plotting mathematical functions and does not directly compete with generate-function. However, it can be used in conjunction with generate-function to dynamically create and plot functions.
escodegen
Escodegen is a code generator for ECMAScript. It's more general-purpose than generate-function, as it can generate code for entire programs or AST nodes, not just functions. It's more complex and powerful but also has a steeper learning curve.
generate-function
Module that helps you write generated functions in Node
npm install generate-function
Disclamer
Writing code that generates code is hard.
You should only use this if you really, really, really need this for performance reasons (like schema validators / parsers etc).
Usage
const genfun = require('generate-function')
const { d } = genfun.formats
function addNumber (val) {
const gen = genfun()
gen(`
function add (n) {')
return n + ${d(val)}) // supports format strings to insert values
}
`)
return gen.toFunction()
}
const add2 = addNumber(2)
console.log('1 + 2 =', add2(1))
console.log(add2.toString())
If you need to close over variables in your generated function pass them to toFunction(scope)
function multiply (a, b) {
return a * b
}
function addAndMultiplyNumber (val) {
const gen = genfun()
gen(`
function (n) {
if (typeof n !== 'number') {
throw new Error('argument should be a number')
}
const result = multiply(${d(val)}, n + ${d(val)})
return result
}
`)
return gen.toFunction({multiply})
}
const addAndMultiply2 = addAndMultiplyNumber(2)
console.log(addAndMultiply2.toString())
console.log('(3 + 2) * 2 =', addAndMultiply2(3))
You can call gen(src)
as many times as you want to append more source code to the function.
Variables
If you need a unique safe identifier for the scope of the generated function call str = gen.sym('friendlyName')
.
These are safe to use for variable names etc.
Object properties
If you need to access an object property use the str = gen.property('objectName', 'propertyName')
.
This returns 'objectName.propertyName'
if propertyName
is safe to use as a variable. Otherwise
it returns objectName[propertyNameAsString]
.
If you only pass gen.property('propertyName')
it will only return the propertyName
part safely
License
MIT